package YAVMM::HostDB::Plugin::MongoDB;
use Moose::Role;

use MooseX::Method::Signatures;

use TryCatch;
use Dancer ':moose';

#use MongoDB;

our $VERSION = '0.01';

with 'YAVMM::Role::MongoDB';

#has '+collection' => ( default => 'yavmm_hosts' );

method add_host (YAVMM::Host $host) {
    $self->update_host($host);
}

method update_host (YAVMM::Host $host) {

    my $host_packed = $host->pack;
    $host_packed->{stats} = 0;

    if (not $self->_coll->update(
	{ 'name' => $host->name },
	{
	    '$set' => $host_packed
		#{
		#'name'     => $host->name,
		#'num_cpus' => $host->num_cpus,
		#'ram'      => $host->ram,
		#'cluster'  => $host->cluster,
		#'stats'    => 0,
	    #}
	},
	{ 'upsert' => 1 })
    ){
	my $err = $self->_db->last_error();
	my $estr = $err->{err} ||= '';
	die YAVMM::Error::DBError->new(
	    error => "Unable to set setting: $estr",
	);
    }
}

method delete_host (YAVMM::Host $host) {
}

method get_host (Str $name) {

    my $obj = $self->_coll->find_one(
	{
	    'name'  => $name,
	    'stats' => 0,
	},
    );

    my $host = $self->_host_from_record($obj);

    return $host;
}

method get_hosts (Str $cluster?) {
    my $query = {};
    if ($cluster) {
	$query->{cluster} = $cluster;
    }

    # Note: Can't sort with snapshot.
    my $cursor = $self->_coll->query(
	$query,
	#{'sort_by' => { 'name' => 1 }},
    )
	->snapshot;

    #use Data::Dumper; debug '$cursor: ', Dumper $cursor;

    if (not $cursor) {
	my $err = $self->_db->last_error();
	my $estr = $err->{err} ||= '';
	die YAVMM::Error::DBError->new(
	    error => "Unable to get hosts: $estr",
	);
    }

    #use Data::Dumper;

    my @hosts = ();
    while (my $obj = $cursor->next) {
	#debug '$cursor->next', Dumper $obj;
	push @hosts, $self->_host_from_record($obj);
    }

    #debug '@hosts: ', Dumper \@hosts;

    # Explicitly sorting since the I can't sort with snapshot
    return sort { $a->name() cmp $b->name() } @hosts;
}

method get_clusters () {
    # WTF? MondgoDB.pm doesn't support distinct natively?
    # http://search.cpan.org/~kristina/MongoDB-0.42/lib/MongoDB/Examples.pod#DATABASE_COMMANDS
    my $result = $self->_db->run_command([
	'distinct' => $self->collection,
	'key'      => 'cluster',
	'query'    => { stats => 0 },
    ]);

    #use Data::Dumper; debug '$result: ', Dumper $result;

    return sort @{ $result->{values} };
}

method _host_from_record (HashRef $obj) {
#    my $host = YAVMM::Host->new(
#	name     => $obj->{name},
#	num_cpus => $obj->{num_cpus},
#	ram      => $obj->{ram},
#	cluster  => $obj->{cluster},
#    );

    my $host = YAVMM::Host->unpack($obj);

    return $host;
}

#__PACKAGE__->meta->make_immutable;
1;

__END__
